<?php
class Cms_CreateUpdate extends Cms_Abstract
{
	public function getColumns()
	{
		$columns = array();
		
		// Columns from the own table
		$columns['local'] = $this->getAdapter()->getColumnsFromTable();
		
		$primary = $this->getAdapter()->getPrimaryKey();
		
		// Foreign Key list
		foreach($columns['local'] as $key => $column)
		{
			// Rename column name to show in the view
			$columns['local'][$key]['view_name'] = $this->getAdapter()->rename(
				$column['column_name'], $primary
			);
			
			if(!empty($column['reference'])) {
				$columns['local'][$key]['reference'] = $this->getAdapter()
					->getForeignList($column['reference']);
			}
		}
		$columns['nms'] = $this->getAdapter()->getNmList();
		return $columns;
	}
	
	public function getTableRowToEdit($viewData)
	{
		$result = array();
		
		$read = Cms::factory(
			'Read',
			$this->getAdapter()->getTable(),
			$this->getAdapter()->getSchema()
		);
		
		$data = $read->getAdapter()->getTableRow(array(
			$this->_request()->getParam('c') => $this->_request()->getParam('v')
		));
		
		foreach($viewData['local'] as $column)
		{
			$value = $data[$column['column_name']];
			
			if($column['type'] == 'boolean') {
				$value = ($value == false) ? 'false' : 'true';
			}
			
			$result['local'][$column['column_name']] = $value;
			if($column['notnull'] && empty($column['auto_incr'])) {
				$result['required'][$column['column_name']] = $column['type'];
			}
		}
		
		foreach($this->getAdapter()->getNmList() as $nm)
		{
			$cms = Cms::factory(
				'Read',
				$nm['info']['table'],
				$nm['info']['schema']
			);
			
			$nmData['info'] = $nm['info'];
			
			$nmAll = $cms->getAdapter()->getTableAll(array(
				$nm['info']['field'] => $data[$nm['info']['local']]
			));
			foreach($nmAll as $nmKey => $nmFields)
			{
				foreach($nm['columns'] as $nmCol)
				{
					$nmValue = $nmFields[$nmCol['column_name']];
					if($nmCol['type'] == 'boolean') {
						$nmValue = ($value == false) ? 'false' : 'true';
					}

					$nmData['columns'][$nmCol['column_name']] = $nmValue;

					if($nmCol['notnull'] && empty($nmCol['auto_incr'])) {
						$nmData['required'][$nmCol['column_name']] = $nmCol['type'];
					}
				}
				$result['nm'][$nmKey] = $nmData;
			}
			
		}
		return $result;
	}
	
	public function save($post)
	{
		$result = array();
		
		$validation = $this->_validateForm($post);
		
		if(empty($validation))
		{
			$column = $this->_request()->getParam('c', false);
			$value = $this->_request()->getParam('v', false);

			$where = null;
			
			if($column && $value)
			{
				$db = Zend_Db_Table::getDefaultAdapter();
				$where = $db->quoteInto(
					"$column = ?", $value,
					(is_numeric($value) ? 'integer' : null)
				);
			}
			
			try {
				$pk = $this->getAdapter()->save($post['local'], $where);
				if(!empty($where)) {
					$pk = $value;
				}
			} catch(Exception $e) {
				$result = array(
					'errors' => true,
					'type' => 'transaction',
					'messages' => $e->getMessage()
				);
			}
			
			if(empty($result) && isset($post['nm'])) {
				$result = $this->_saveNms($pk, $post['nm'], $where);
			}
		} else {
			$result = array('errors' => true, 'messages' => $validation);
		}
		
		return $result;
	}
	
	public function _saveNms($pk, $nms)
	{
		$response = array();
		
		$tablesDone = array();
		
		foreach($nms as $data)
		{
			$table = $data['info']['schema'].'.'.$data['info']['table'];
			try {
				// Verify if the data from this table was not deleted yet
				if(!in_array($table, $tablesDone))
				{
					$del = Cms::factory(
						'Delete', $data['info']['table'], $data['info']['schema']
					);

					// Delete old relations and create all over again
					$response = $del->getAdapter()->deleteRow(array(
						'c' => $data['info']['field'], 'v' => $pk
					));
					
					$tablesDone[] = $table;
				}

				// Fk from local table into
				$data['columns'][$data['info']['field']] = $pk;

				$cms = Cms::factory(
					'CreateUpdate',
					$data['info']['table'],
					$data['info']['schema']
				);

				// Create a new relation
				$cms->getAdapter()->save($data['columns']);
			} catch(Exception $e) {
				$response['errors'] = false;
				$response['type'] = 'nms';
				$response['messages'][] = 'Alguns dados não puderam ser '
					.'alterados corretamente, provavelmente outra parte do '
					.'sistema depende desta informação para viver';
				
				// @TODO: Inserir log aqui
			}
		}
		
		return $response;
	}
	
	private function _validateForm($post)
	{
		$errors = array();
		
		$validate = new Validate();
		
		// Local table fields
		$validate->setRules(
			$this->getAdapter()->getTableParams('validate'),
			$this->getAdapter()->getValidationTypes($post['required'])
		);
		$errors['local'] = $validate->check($post['local']);
		
		// NM fields
		if(isset($post['nm'])) {
			foreach($post['nm'] as $keyNm => $fieldNm) {
				$cms = Cms::factory(
					'CreateUpdate',
					$fieldNm['info']['table'],
					$fieldNm['info']['schema']
				);
				
				$validate->setRules(
					$cms->getAdapter()->getTableParams('validate'),
					$cms->getAdapter()->getValidationTypes($fieldNm['required'])
				);
				$errors['nm'][$keyNm] = $validate->check($fieldNm['columns']);
			}
		}
		
		return $errors;
	}
}